package org.dragon.advices;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/5/17 10:50
 */
import com.fasterxml.jackson.core.JsonProcessingException;
import org.dragon.commons.Const;
import org.dragon.commons.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalRestResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private MappingJackson2HttpMessageConverter jackson2HttpMessageConverter;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        var type = returnType.getParameterType();
        return !type.equals(JsonResult.class) && !type.equals(ResponseEntity.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 处理返回值
        if (body instanceof String) {
            try {
                response.getHeaders().set(Const.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                return jackson2HttpMessageConverter.getObjectMapper()
                        .writeValueAsString(JsonResult.ok(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        return body == null ? JsonResult.ok() : JsonResult.ok(body);
    }
}